package com.code.splider.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import com.code.splider.service.HttpClientService;

@Service()
public class HttpClientServiceImpl implements HttpClientService{

	@Override
	public void beginGrap(String url) {
		// TODO Auto-generated method stub
//		HttpClientUtils.doGet(url);

        //创建默认的httpClient实例
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse httpResponse = null;
        try {
            //用get方法发送http请求
            HttpGet get = new HttpGet(url);
            System.out.println("执行get请求:...."+get.getURI());

            //发送get请求
            httpResponse = httpClient.execute(get);

        }catch( UnsupportedEncodingException e){
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
            e.printStackTrace();
        }catch(ClientProtocolException e){
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
            e.printStackTrace();
        }catch (IOException e) {
            // 发生网络异常
            e.printStackTrace();
        }catch (Exception e) {
            // 发生网络异常
            e.printStackTrace();
        }finally{
            try{
                httpResponse.close();
                closeHttpClient(httpClient);
            } catch(Exception e){
                e.printStackTrace();
            }
        }
    }

	private static CloseableHttpClient getHttpClient(){
        return HttpClients.createDefault();
    }

    private static void closeHttpClient(CloseableHttpClient client) throws IOException{
        if (client != null){
            client.close();
        }
    }
}
